<?php
class AlbumEtaoAction extends CommonAction
{
	public function index(){
		$model = M();
		$sql = 'SELECT COUNT(DISTINCT a.id) AS tcount 
			FROM '.C("DB_PREFIX").'album_etao AS a, '.C("DB_PREFIX").'user AS u, '.C("DB_PREFIX").'album AS b where u.uid = a.uid and a.album_id=b.id';

		$count = $model->query($sql);
		$count = $count[0]['tcount'];
		
		$sql = 'SELECT a.id,a.etao_id,a.etao_name,a.uid,u.user_name,a.album_id,b.title,(a.create_time-8*60*60) as create_time,a.status 
			FROM '.C("DB_PREFIX").'album_etao AS a, '.C("DB_PREFIX").'user AS u, '.C("DB_PREFIX").'album AS b where u.uid = a.uid and a.album_id=b.id';
		$this->_sqlList($model,$sql,$count);
		
		$this->display();
		return;		
	}
	
	public function etaolog(){
		$model = M();
		$sql = 'SELECT COUNT(DISTINCT id) AS tcount FROM '.C("DB_PREFIX").'album_etao_log';

		$count = $model->query($sql);
		$count = $count[0]['tcount'];
		
		$sql = 'SELECT id,etao_id,iday,(create_time-8*60*60) as create_time,down_url,size,line FROM '.C("DB_PREFIX").'album_etao_log';
		$this->_sqlList($model,$sql,$count);
		
		$this->display();
		return;		
	}	
	
	public function insert(){
		$name=$this->getActionName();
		$model = D($name);
		if(false === $data = $model->create()){
			$this->error($model->getError());
		}else{
			$sql = "select count(id) as tcount from ".C("DB_PREFIX").'album where uid='. $_POST['uid'].' and id='.$_POST['album_id'];
			$count = M()->query($sql);
			$count = $count[0]['tcount'];
			if($count==0){
				$this->error("该编辑ID：".$_POST['uid'].' 下没有编号为: '.$_POST['album_id'].'的专辑！');
			}
		}
		
		//保存当前数据对象
		$sql = "insert into ".C("DB_PREFIX")."album_etao(uid,album_id,etao_id,etao_name,create_time) values(". $_POST['uid'].",". $_POST['album_id'].",". $_POST['etao_id'].",'". $_POST['etao_name']."',".time().")";
		$list = M()->execute($sql);
		if ($list !== false)
		{
			$this->success (L('ADD_SUCCESS'));
		}
		else
		{
			$this->error (L('ADD_ERROR'));
		}
	}
	
	public function update(){
		$id = intval($_REQUEST['id']);
		$name=$this->getActionName();
		$model = D ($name);
		if (false === $data = $model->create ()) {
			$this->error ( $model->getError () );
		}else{
			$sql = "select count(id) as tcount from ".C("DB_PREFIX").'album where uid='. $_POST['uid'].' and id='.$_POST['album_id'];
			$count = M()->query($sql);
			$count = $count[0]['tcount'];
			if($count==0){
				$this->error("该编辑ID：".$_POST['uid'].' 下没有编号为: '.$_POST['album_id'].'的专辑！');
			}
		}
		// 更新数据
		$sql = "update ".C("DB_PREFIX")."album_etao set uid= ".$_POST['uid'].",album_id=".$_POST['album_id'].",etao_id=".$_POST['etao_id'].",etao_name='".$_POST['etao_name']."' where id=".$id;
		$list = M()->execute($sql);
		if (false !== $list)
		{	
			$this->saveLog(1,$id);
			$this->assign('jumpUrl', Cookie::get ( '_currentUrl_' ) );
			$this->success (L('EDIT_SUCCESS'));
		}
		else
		{
			//错误提示
			$this->saveLog(0,$id);
			$this->error (L('EDIT_ERROR'));
		}
	}
	
	public function remove(){
		//删除指定记录
		$result = array('isErr'=>0,'content'=>'');
		$id = $_REQUEST['id'];
		if(!empty($id))
		{
			$sql = "delete from ".C("DB_PREFIX")."album_etao where id=".$id;
			$list = M()->execute($sql);
			if(false !== $list)
			{
				$this->saveLog(1,$id);
			}
			else
			{
				$this->saveLog(0,$id);
				$result['isErr'] = 1;
				$result['content'] = L('REMOVE_ERROR');
			}
		}
		else
		{
			$result['isErr'] = 1;
			$result['content'] = L('ACCESS_DENIED');
		}
		
		die(json_encode($result));
	}
	
    public function getTags($gid){
       $tabs=M("share_tags");
       $r=$tabs->where("share_id={$gid}")->select();
       $tags=array();
       foreach ($r as $key => $value) {
           array_push($tags,$value['tag_name']);
       }
       return join(chr(0x2),$tags);
    }
	public function export(){
        header('Content-Type: text/html; charset=UTF-8');
        $basePath=STRENDS_ROOT.'etao_new';
        $exp_id=Session::get('exp_id');
        if($_GET[r]==1){
            if($exp_id){
                Session::set('exp_id',NULL);
                F('albums_'.$exp_id,NULL);
                $dir=DATA_PATH.'items_'.$exp_id;
                if(is_dir($dir)){
                    $sd=new Dir();
                    $sd->delDir($dir);
                }
            }
            exit('已经清除！');
        }
        
        if(!$exp_id){
            $exp_id=strtotime(now);
            $path=$basePath.'/'.$exp_id;
            mkdir($path);
            Session::set('exp_id',$exp_id);
            //杂志社
            $albums=array();
            $album=M('album_etao');
            $albumids=$album->Distinct(true)->field('etao_id')->select();
            foreach ($albumids as $key => $value) {
                $as=$album->where('etao_id='.$value[etao_id])->select();
                if(!$as) continue;
                $albums[$key][etao_id]=$value[etao_id];
                $albums[$key][etao_name]=$as[0][etao_name];
                $als=array();
                foreach ($as as $k => $v) {
                    array_push($als,$v[album_id]);
                }
                $albums[$key][album_ids]=join(',',$als);
            }
            F('albums_'.$exp_id,$albums);
        }else{
            $path=$basePath.'/'.$exp_id;
            $albums=F('albums_'.$exp_id);
        }
        $step=500;$dir='items_'.$exp_id.'/';
        $tab=D('EtaoShare');$tabshare=M('share');
        $album_ids=$albums[0][album_ids];
        $etao_id=$albums[0][etao_id];
        $etao_name=$albums[0][etao_name];
        date_default_timezone_set('Asia/Shanghai');
        if(!$etao_id){
            Session::set('exp_id',NULL);
            $this->display();
            exit;
        }
        
        if($_POST[etao_id]>0){
            $list=$tab->Distinct(true)->where('album_share.album_id in('.$album_ids.')')->limit($_POST[begin].','.$_POST['end'])->select();
            $d=F($dir.'data_'.$etao_id);
            if($list && count($d)<5000){
                if(!is_array($d))$d=array();
                foreach ($list as $k => $v) {
                    if(empty($v[name])) continue;
                    $ds=array();
                    array_push($ds,$v[name]);//标题
                    array_push($ds,$v[price]);//价格
                    $img=$v[keyimg_url];
                    if(empty($img)){
                        if($v[base_share]>0){
                            $img=M('share_goods')->where('share_id='.$v[base_share])->getField('keyimg_url');
                        }else{
                           if($v[base_id]>0){
                                $img=M('share_goods')->where('goods_id='.$v[base_id])->getField('keyimg_url');
                            } 
                        }
                    }
                    array_push($ds,$img);//图片url
                    array_push($ds,'');//评论
                    array_push($ds,'');//收藏数
                    array_push($ds,'');//标签
                    array_push($ds,'');//分类
                    
                    $url=$v[url];
                    $uri=explode('&',$url);
                    if(is_array($uri)) $url=$uri[0];
                    array_push($ds,$url);//购买链接
                    array_push($ds,"http://www.tiemeili.com/note.php?action=g&sid=$v[share_id]&id=$v[goods_id]");//合作伙伴url
                    
                    $stime=$tabshare->where('share_id='.$v[share_id])->getField('create_time');
                    if($stime){
                        $t=date("Y-m-d H:i:s",$stime);
                    }
                    array_push($ds, date("Y-m-d H:i:s",strtotime("$t + 8 hour")));//时间处理
                    array_push($ds,$etao_id);//一淘所属频道ID
                    if(in_array(join(chr(0x1),$ds),$d)) continue;                  
                    array_push($d,join(chr(0x1),$ds));
                }
                F($dir.'data_'.$etao_id,$d);
                $begin=$_POST[begin] + $step;
                $end=$begin + $step -1;
            }else{
               $d=F($dir.'data_'.$etao_id);
               $count=count($d);
               if($count>0){
                  $dir1=$basePath."/".$exp_id."/";
                  if(!is_dir($dir1)) mkdir($dir1);
                  $fname=$albums[0][etao_id].".".$albums[0][etao_name].'.'.date('Ymd').".txt";
                  $file=$dir1.$fname;
                  $of=fopen($file,'w');
                  foreach ($d as $key => $value) {
                      fwrite($of,$value."\r\n");
                  }
                  fclose($of);
                   $log=M('album_etao_log');
                   $arr[create_time]=strtotime(now);
                   $arr[iday]=date('Ymd');
                   $arr[line]=$count;
                   $arr[etao_id]=$albums[0][etao_id];
                   $arr[etao_name]=$albums[0][etao_name];
                   $arr[down_url]='/'.'etao_new/'.$exp_id.'/'.$fname;
                   $log->add($arr);
               }
               array_splice($albums,0,1);
               F('albums_'.$exp_id,$albums);
               $begin=0;$end=$step-1;
            }            
        }else{
            $begin=0;$end= $begin + $step -1;
        }
        $this->assign('etao_id',$etao_id);
        $this->assign('etao_name',$etao_name);
        $this->assign('begin',$begin);
        $this->assign('end',$end);
        $this->display();
	}

	public function toggleStatus()
	{
		$id = intval($_REQUEST['id']);
		if($id == 0)
			exit;
		
		$val = intval($_REQUEST['val']) == 0 ? 1 : 0;
			
		$field = trim($_REQUEST['field']);
		if(empty($field))
			exit;
		
		$result = array('isErr'=>0,'content'=>'');
		$sql = "update ".C("DB_PREFIX")."album_etao set ".$field."= ".$val." where id=".$id;
		$list = M()->execute($sql);
		if(false !== $list)
		{
			$this->saveLog(1,$id,$field);
			$result['content'] = $val;
		}
		else
		{
			$this->saveLog(0,$id,$field);
			$result['isErr'] = 1;
		}
		
		die(json_encode($result));
	}	
}
?>